package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.mapper.VmTypeMapper;
import com.heima.pojo.dto.VmTypeAddDto;
import com.heima.pojo.dto.VmTypeSearchDto;
import com.heima.pojo.dto.VmTypeUpdateDto;
import com.heima.pojo.entity.VmType;
import com.heima.pojo.vo.PageResponseVo;
import com.heima.pojo.vo.VmTypeVo;
import com.heima.service.VmTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class VmTypeServiceImpl extends ServiceImpl<VmTypeMapper, VmType> implements VmTypeService {
    @Override
    public PageResponseVo<VmTypeVo> selectVmType(VmTypeSearchDto vmTypeSearchDto) {
        Page<VmType> vmTypePage = new Page<>(vmTypeSearchDto.getPageIndex(), vmTypeSearchDto.getPageSize());
        LambdaQueryWrapper<VmType> wrapper = new LambdaQueryWrapper<>();
        if (vmTypeSearchDto.getName() != null) {
            wrapper.eq(VmType::getName, vmTypeSearchDto.getName());
        }
        Page<VmType> page = this.page(vmTypePage, wrapper);
        List<VmTypeVo> voList = page.getRecords().stream()
                .map(vmType -> {
                    VmTypeVo vo = new VmTypeVo();
                    BeanUtils.copyProperties(vmType, vo);
                    return vo;
                })
                .collect(Collectors.toList());

        //封装响应数据对象
        PageResponseVo<VmTypeVo> Vo = new PageResponseVo<>();
        Vo.setPageSize(vmTypeSearchDto.getPageSize());
        Vo.setPageIndex(vmTypeSearchDto.getPageIndex());
        Vo.setTotalCount(page.getTotal());
        Vo.setTotalPage(page.getPages());
        Vo.setCurrentPageRecords(voList);
        return Vo;
    }

    @Override
    public Boolean addVmType(VmTypeAddDto vmTypeAddDto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(vmTypeAddDto, vmType);
        return this.save(vmType);
    }

    @Override
    public Boolean updateVmTypeByTypeId(Integer typeId, VmTypeUpdateDto vmTypeUpdateDto) {
        LambdaQueryWrapper<VmType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VmType::getTypeId, typeId);
        VmType vmType = new VmType();
        BeanUtils.copyProperties(vmTypeUpdateDto, vmType);
        return this.update(vmType, wrapper);
    }

    @Override
    public Boolean deleteVmTypeByTypeId(Integer typeId) {
       return  this.removeById(typeId);
    }

}
